<template>
  <list-page>
    <pub-search
      v-model:searchColumns="searchColumns"
      v-model:search-form="searchForm"
      mask-append-to="table-content"
      @search="search"
    >
      <template #leftBtn>
        <el-button
          v-hasPermissions="['basic:system:account:add']"
          type="primary"
          @click="add"
          :icon="Plus"
        >
          新增
        </el-button>
      </template>
    </pub-search>
    <pub-table
      ref="pubTable"
      :column="columns"
      :data="tableData"
      :loading="tableLoading"
    >
      <template v-slot:userType="scope">
        {{
          scope.row.userType == 1
            ? '总部'
            : scope.row.userType == 2
            ? '街道中心'
            : scope.row.userType == 3
            ? '社区服务站'
            : scope.row.userType == 4
            ? '助老员'
            : '--'
        }}
      </template>
      <template v-slot:switch="scope">
        <el-switch
          :before-change="beforeChangeColumn"
          v-model="scope.row.status"
          active-color="#13ce66"
          inactive-color="#ff4949"
          :active-value="1"
          :inactive-value="0"
          @change="changeStatus(scope.row)"
        />
      </template>
      <template v-slot:option="scope">
        <el-button
          v-hasPermissions="['basic:system:account:edit']"
          plain
          type="primary"
          @click="edit(scope.row)"
        >
          编辑
        </el-button>
        <el-button
          v-if="
            scope.row.userType != 2 &&
            scope.row.userType != 3 &&
            scope.row.userType != 4
          "
          v-hasPermissions="['basic:system:account:delete']"
          plain
          type="primary"
          @click="del(scope.row)"
        >
          删除
        </el-button>
        <el-dropdown style="margin-left: 20px" size="medium">
          <el-button type="primary">
            更多
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="reset(scope.row)">
                <span v-hasPermissions="['basic:system:account:reset']">
                  重置密码
                </span>
              </el-dropdown-item>
              <el-dropdown-item @click="auth(scope.row)">
                <span
                  v-if="
                    scope.row.userType != 2 &&
                    scope.row.userType != 3 &&
                    scope.row.userType != 4
                  "
                  v-hasPermissions="['basic:system:account:auth']"
                >
                  权限分配
                </span>
              </el-dropdown-item>
              <el-dropdown-item @click="cancel(scope.row)">
                <span v-hasPermissions="['basic:system:account:cancel']">
                  解除锁定
                </span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </pub-table>
    <!-- 添加/编辑弹窗 -->
    <pub-dialog
      v-if="dialogFormVisible_add"
      :title="popTitle"
      :hasExtraBtn="true"
      v-model:visible="dialogFormVisible_add"
      width="600px"
    >
      <dialogEdit
        ref="dialogEditRef"
        @close="close"
        @submitForm="submitForm"
        :editData="editData"
        :isEdit="isEdit"
      ></dialogEdit>
    </pub-dialog>
    <!-- 添加/编辑弹窗 -->
    <pub-dialog
      v-if="showDialogAdd"
      :title="popTitle"
      :hasExtraBtn="true"
      v-model:visible="showDialogAdd"
      width="600px"
    >
      <authBind
        ref="dialogEditRef"
        @close="showDialogAdd = false"
        @submitForm="bindSubmit"
        :roleId="currentRoleId"
      ></authBind>
    </pub-dialog>
    <pub-pagination
      :total="pagination.total"
      v-model:page="pagination.page"
      v-model:limit="pagination.pageSize"
      @pagination="pagination.change"
    ></pub-pagination>
  </list-page>
</template>
<script>
export default {
  name: 'roles'
}
</script>
<script setup>
import dialogEdit from './components/add.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { Sm4encrypt, Sm4Dncrypt } from '@/utils/encryption.js'
import authBind from './components/authBind.vue'
import {
  add_account,
  edit_account,
  delete_account,
  get_account_list,
  reset_password,
  cancel_account,
  bind_roles
} from '@/api/system'
import { useTable } from '@/hooks/UseTable'
const editData = ref({})
const popTitle = ref('')
const isEdit = ref(false)
const switchState = ref(false)
const editId = ref('')
const showDialogBindList = ref(false)
const dialogFormVisible_add = ref(false)
const total = ref(0)
const showDialogAdd = ref(false)
let { tableData, search, getList, pagination, searchForm, tableLoading } =
  useTable(get_account_list)
const dialogEditRef = ref()
const currentId = ref()
const columns = ref([
  { label: '真实姓名', prop: 'realName' },
  { label: '登录账号', prop: 'userName' },
  {
    label: '手机号码',
    prop: 'telephone'
  },
  {
    label: '用户类型',
    prop: 'userType',
    type: 'slot',
    slot: 'userType'
  },
  {
    label: '绑定角色',
    prop: 'roleNames'
  },
  { label: '是否禁用', type: 'switch', prop: 'status' },
  {
    label: '创建时间',
    prop: 'createDate'
  },
  { label: '操作', type: 'option', width: '220' }
])
const searchColumns = ref([
  {
    label: '真实姓名',
    el: 'Input',
    bind: 'realName',
    defaultValue: '',
    labelWidth: 80
  },
  {
    label: '登录账号',
    el: 'Input',
    bind: 'userName',
    defaultValue: '',
    labelWidth: 80
  }
])

onMounted(() => {
  getList()
})

const bindSubmit = async val => {
  let data = {
    roleId: val.roleId,
    userId: currentId.value
  }
  if (isEdit.value) {
    data.id = val.id
  }
  let res = await bind_roles(data)
  if (res.succeed) {
    ElMessage.success(res.msg)
  }
  getList()
  showDialogAdd.value = false
}

const beforeChangeColumn = () => {
  switchState.value = true
  return switchState.value
}

const changeStatus = row => {
  if (switchState.value) {
    const params = {
      id: row.id,
      status: row.status
    }
    enable_roles(params).then(result => {
      if (result.succeed) {
        getList()
        ElMessage({
          type: 'success',
          message: result.msg
        })
      }
    })
  }
}

const add = row => {
  popTitle.value = '新增'
  dialogFormVisible_add.value = true
  isEdit.value = false
}

const edit = row => {
  popTitle.value = '编辑'
  editData.value = JSON.parse(JSON.stringify(row))
  dialogFormVisible_add.value = true
  isEdit.value = true
}

const close = () => {
  editId.value = ''
  dialogFormVisible_add.value = false
  showDialogBindList.value = false
}

const reset = row => {
  ElMessageBox.confirm('此操作将为该用户生成新密码, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      tableLoading.value = true
      let res = await reset_password({ id: row.id, operateType: '1' })
      if (res.succeed) {
        ElMessageBox.alert(
          `重置密码成功！重置后的密码是：${Sm4Dncrypt(res.data)}`,
          {
            confirmButtonText: '确定',
            callback: action => {}
          }
        )
        search()
      }
      tableLoading.value = false
    })
    .catch(() => {})
}
const currentRoleId = ref(null)
const auth = row => {
  currentRoleId.value = row.roleIds
  currentId.value = row.id
  showDialogAdd.value = true
}

const cancel = async row => {
  ElMessageBox.confirm('是否解锁此账号?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      tableLoading.value = true
      let res = await cancel_account({ id: row.id })
      if (res.succeed) {
        ElMessage({
          type: 'success',
          message: res.msg
        })
        search()
      }
      tableLoading.value = false
    })
    .catch(() => {})
}

const del = row => {
  ElMessageBox.confirm('确认删除选择的记录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      tableLoading.value = true
      delete_account(row.id).then(res => {
        if (res.succeed) {
          ElMessage({
            type: 'success',
            message: res.msg
          })
          search()
        }
        tableLoading.value = false
      })
    })
    .catch(() => {})
}

const submitForm = async data => {
  try {
    if (isEdit.value) {
      // 修改角色
      const res = await edit_account(data)
      if (res.succeed) {
        ElMessage({
          type: 'success',
          message: res.msg
        })
      }
    } else {
      // 新增角色
      const res = await add_account(data)
      if (res.succeed) {
        ElMessageBox.alert(`${res.msg}初始密码为：${Sm4Dncrypt(res.data)}`, {
          confirmButtonText: '关闭',
          callback: action => {}
        })
      }
    }
    isEdit.value = false
    close()
    await search()
  } catch (error) {
    console.log('error', error)
  }
  // dialogEditRef.value.loadClose()
}
</script>
<style lang="scss" scoped>
.table-container {
  height: calc(100% - 90px);
}
.container {
  width: 100%;
  height: 100vh;
  padding: 10px;
}
</style>
